import { ElMessage } from 'element-plus'
import store from "@/store";
import { defineStore } from "pinia"
import api from "@/views/ai/agent/utils/request/BaseRequest"

export const userSocket = defineStore('userSocket', {
  state: () => ({
    socket: undefined,
    socketId: undefined,
    // 在线人数
    onlineCount: 0
  }),
  mutations: {
  },
  actions: {
    // 用户socket连接
    ConnectUserSocket() {
      const userId = store.userStore.user.id
      if (userId != null){
        return new Promise((resolve, reject) => {

          const websocketUrl = store.webConfig.resourceMain.websocketUrl;
          const wsUrl = websocketUrl +'/socket/user/' + userId;
          const webSocket = new WebSocket(wsUrl);

          webSocket.onmessage = function (event) {
            let data = event.data;
            handleSocketData(data)
          };

          webSocket.onclose = function () {
          }
          webSocket.onerror = function () {
          }

          this.$state.socket = webSocket
          resolve("")
        })
      }
    },

    // 清除连接信息
    ClearSocketInfo() {
      return new Promise((resolve, reject) => {
        this.$state.socket = undefined
        this.$state.socketId = undefined

        resolve("")
      })
    }

  }
})


/**
 * socket 消息处理
 * @param val
 */
function handleSocketData(val) {
  if (val == null || val === ''){
    return
  }
  const data = JSON.parse(val);

  // 弹窗推送
  const code = data.code;
  const resData = data.data;
  switch (code) {

    // 初始化
    case 0:
      store.commit('SET_SOCKET_ID',resData);
      break;

    // 通知
    case 2:
      // Message({message: data.message, type: 'success'})
      ElMessage.success(data.message)
      break;
    case 3:
      // Message({message: data.message, type: 'warning'})
      ElMessage.warning(data.message)
      break;
    case 4:
      // Message({message: data.message, type: 'error'})
      ElMessage.error(data.message)
      break;

    // 在线人数
    case 11:
      this.$state.onlineCount = resData
      break;
  }

}

export default userSocket
